#include <iostream>
#include <vector>
#include <functional>
#include <algorithm>

// 观察者接口
template<typename T>
class Observer {
public:
    virtual ~Observer() = default;
    virtual void update(const T& data) = 0;
};

// 被观察者基类
template<typename T>
class Subject {
private:
    std::vector<Observer<T>*> observers_;

public:
    void attach(Observer<T>* observer) {
        observers_.push_back(observer);
    }
    
    void detach(Observer<T>* observer) {
        observers_.erase(
            std::remove(observers_.begin(), observers_.end(), observer),
            observers_.end()
        );
    }
    
    void notify(const T& data) {
        for (auto observer : observers_) {
            observer->update(data);
        }
    }
};

// 具体的被观察者
class Button : public Subject<std::string> {
private:
    std::string name_;
    
public:
    Button(const std::string& name) : name_(name) {}
    
    void click() {
        std::cout << "Button " << name_ << " clicked!" << std::endl;
        notify("clicked: " + name_);
    }
    
    void hover() {
        std::cout << "Button " << name_ << " hovered!" << std::endl;
        notify("hovered: " + name_);
    }
};

// 具体观察者
class Logger : public Observer<std::string> {
public:
    void update(const std::string& data) override {
        std::cout << "[LOG] Event: " << data << std::endl;
    }
};

class Analytics : public Observer<std::string> {
public:
    void update(const std::string& data) override {
        std::cout << "[ANALYTICS] Tracking: " << data << std::endl;
    }
};

// 使用示例
int main() {
    Button button1("Submit");
    Button button2("Cancel");
    
    Logger logger;
    Analytics analytics;
    
    // 注册观察者
    button1.attach(&logger);
    button1.attach(&analytics);
    button2.attach(&logger);
    
    // 触发事件
    button1.click();
    button2.click();
    button1.hover();
    
    return 0;
}